//============================================================================
// Name        : herausRAGEnd.cpp
// Author      : bossfong@omail.pro
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include "ProcessWin.h"
#include "ProcessIteratorWin.h"

MemoryAddress getNetvaroffset(const std::string& datatable, const std::string& propname, const byte propsize, MemoryRegion& client, MemoryReader& reader)
{
	address_t propname_ptr = client.findString(propname);
	MemoryAddress actual_dt_name_ptr = client.findString(datatable);

	byte propname_ptr_1, propname_ptr_2, propname_ptr_3, propname_ptr_4;
	propname_ptr_1 = ((propname_ptr>>24)&0xff);
	propname_ptr_2 = ((propname_ptr>>16)&0xff);
	propname_ptr_3 = ((propname_ptr>>8 )&0xff);
	propname_ptr_4 = ((propname_ptr>>0 )&0xff);

	std::vector<byte> pattern = { 0x6A, propsize, 0x68, 0x00, 0x00, 0x00, 0x00, 0x68, propname_ptr_4, propname_ptr_3, propname_ptr_2, propname_ptr_1 };

	MemoryAddress found = client.bounds().begin();
	while ((found = client.findPattern("xxx????xxxxx", pattern, found + 1)) != 0)
	{
		MemoryAddress dt_name_ptr = client.findPattern("x????x?x????x", { 0x68, 0x00, 0x00, 0x00, 0x00, 0x6A, 0x00, 0x68, 0x00, 0x00, 0x00, 0x00, 0xB9 }, found);
		if ((address_t)dt_name_ptr.ptr(reader, 1) == (address_t)actual_dt_name_ptr)
		{
			return found.as<address_t>(reader, 3);
		}
	}

	return 0;
}

void offsetScan(ProcessPtr proc)
{
	ProcessModule clientdll = proc->module("client.dll");
	MemoryRegion client = clientdll.asRegion(proc->reader());
	std::cout << "EntityList ptr: " << client.findPattern("xx????xxxxxxxx", { 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x89, 0x45, 0xDC, 0x8B, 0x49, 0x04, 0x3B, 0xCB } ).ptr(proc->reader(), 2).str() << std::endl;
	MemoryAddress localPlayer = client.findPattern("xx????xxxx????x", { 0x8B, 0x35, 0x00, 0x00, 0x00, 0x00, 0x85, 0xF6, 0x0F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x53 } ).ptr(proc->reader(), 2);
	std::cout << "LocalPlayer ptr: " << localPlayer.str() << std::endl;
	MemoryAddress healthOffset = getNetvaroffset("DT_BasePlayer", "m_iHealth", 4, client, proc->reader());
	std::cout << "m_iHealth offset: " << healthOffset.str() << std::endl;
	std::cout << "\t->Localplayer.m_iHealth = " << localPlayer.ptr(proc->reader()).as<int>(proc->reader(), healthOffset) << std::endl;
	//getNetvaroffset("", "m_lifeState", 1, client, proc->reader());
	//getNetvaroffset("", "m_iTeamNum", 4, client, proc->reader());
	//getNetvaroffset("", "m_vecOrigin", 0xC, client, proc->reader());
	//getNetvaroffset("", "m_angRotation", 0xC, client, proc->reader());
}


int main() {
	ProcessIteratorWin it;
	while (++it)
	{
		if ((*it)->name() == "csgo.exe")
		{
			std::cout << "Found csgo.exe!" << std::endl;
			offsetScan(*it);
		}
	}
	return 0;
}
